/*
 *Create By：Z.B
 *@DATE 2019/3/19 15:18
 *@EMAIL: 2545375@qq.com
 */
'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller{

  constructor(ctx) {
    super(ctx);

    this.UserCreateTransfer = {
      mobile: {type: 'string', required: true, allowEmpty: false, format: /^[0-9]{11}$/},
      password: {type: 'password', required: true, allowEmpty: false, min: 6},
      realName: {type: 'string', required: true, allowEmpty: false, format: /^[\u2E80-\u9FFF]{2,6}$/}
    };

    this.UserUpdateTransfer = {
      mobile: { type: 'string', required: true, allowEmpty: false },
      realName: {type: 'string', required: true, allowEmpty: false, format: /^[\u2E80-\u9FFF]{2,6}$/}
    }
  }

  async create(){
    const {ctx, service } = this;

    ctx.validate(this.UserCreateTransfer);

    const payload = ctx.request.body || {};
    //调用service处理
    const res = await service.user.create(payload);
    //设置响应
    ctx.helper.success({ctx,res});
  }

  //删除当个用户
  async destroy(){
    const {ctx, service} = this;

    //获取参数
    const {id} = ctx.params;

    await service.user.destroy(id);
    ctx.helper.success({ctx});
  }

  async show(){
    const {ctx, service} = this;

    //获取参数
    const { id } = ctx.params;

    const res = await service.user.show(id);

    ctx.helper.success({ctx, res});

  }

  async update(){
    const { ctx, service } = this;

    //验证数据
    ctx.validate(this.UserUpdateTransfer);

    const { id } = ctx.params;
    const payload = ctx.request.body;

    await service.user.update(id, payload);

    // 设置响应内容和响应状态码
    ctx.helper.success({ctx});
  }

  async removes(){
    const { ctx, service } = this;

    const { id } = ctx.request.body;

    const payload = id.split(',') || [];

    const res = await service.user.removes(payload);

    ctx.helper.success({ctx});
  }

  async index(){
    const {ctx, service} = this;

    const payload = ctx.query;

    const res = await service.user.index(payload);

    ctx.helper.success({ctx, res});
  }
}

module.exports = UserController;